/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-01-30 20:21:31
 * @LastEditors: Clark
 * @LastEditTime: 2023-01-31 12:40:38
 * @Description: file content
 */

#include "apue.h"
#include <ctype.h>
#include <fcntl.h>

#define BSZ 4096
unsigned char buf[BSZ];

unsigned char translate(unsigned char c)
{
    if (isalpha(c))
    {
        if (c >= 'n')
        {
            c -= 13;
        }
        else if (c >= 'a')
        {
            c += 13;
        }
        else if (c >= 'N')
        {
            c -= 13;
        }
        else
        {
            c += 13;
        }
    }
    return c;
}

int main(int argc, char *argv[])
{
    int ifd;
    int ofd;
    int i, n, nw;

    if (3 != argc)
    {
        err_quit("usage: rot13 infile outfile");
    }

    if ((ifd = open(argv[1], O_RDONLY)) < 0)
    {
        err_sys("cant't open %s", argv[1]);
    }

    if ((ofd = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, FILE_MODE)) < 0)
    {
        err_sys("cant't create %s", argv[2]);
    }

    while ((n = read(ifd, buf, BSZ)) > 0)
    {
        for (int i = 0; i < n; i++)
        {
            buf[i] = translate(buf[i]);
        }

        if ((nw = write(ofd, buf, n)) != n)
        {
            if (nw < 0)
            {
                err_sys("write failed");
            }
            else
            {
                err_quit("short write (%d/%d)");
            }
        }
    }

    fsync(ofd);
    exit(0);
}
